// 卡片管理
// 导入数据库
const db = require("../db/index");

// 发表留言
exports.addWall = (req, res) => {
  const wallInfo = {
    // 内容 时间 发的用户名
    ...req.body,
    moment: new Date(),
    // 作者id
    user_id: req.user.id,
  };
  const sql = ` insert into wall set ?`;
  db.query(sql, wallInfo, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("发布留言失败！");
    res.cc("发布留言成功", 0);
  });
};

// 获取留言
exports.getWall = (req, res) => {
  const sql = `select wall.* ,users.username,users.user_pic from wall,users where wall.is_delete !=1 and wall.user_id = users.id  order by wall.moment desc  `;
  db.query(sql, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      message: "获取留言成功",
      data: results,
      status: 0,
    });
  });
};

// 获取个人留言
exports.getMyWall = (req, res) => {
  // const sql = `select * from wall where user_id = ? and is_delete != 1`;
  const sql = `
  SELECT wall.*, users.username, users.user_pic 
  FROM wall, users 
  WHERE wall.is_delete != 1 
    AND wall.user_id = users.id 
    AND wall.user_id = ? 
  ORDER BY wall.moment DESC
`;

  db.query(sql, [req.user.id], (err, results) => {
    if (err) return err;
    if (results.length == 0) return res.cc("没有查到对应数据！");

    res.send({
      status: 0,
      message: "获取留言成功！",
      data: results,
    });
  });
};

// 删除个人留言
/**
 *
 * @param {params id} req
 * @param {*} res
 */
exports.deleteMyWall = (req, res) => {
  const sql = `update wall set is_delete = ? where id = ? `;
  db.query(sql, [1, req.query.id], (err, results) => {
    if (err) return err;
    if (results.affectedRows !== 1) return res.cc("删除失败！稍后再试");
    res.send({
      status: 0,
      message: "删除成功！",
    });
  });
};

// 点赞
/**
 *  body
 * @param {wall_id} req
 * @param {*} res
 */
exports.updateWallLike = (req, res) => {
  const sql = `update wall set like_num = like_num  + 1 where id = ?`;
  db.query(sql, req.body.wall_id, (err, results) => {
    if (err) return err;
    const sql2 = `insert into wall_like set ?`;
    const likeInfo = {
      ...req.body,
      moment: new Date(),
      // 作者id
      user_id: req.user.id,
    };
    db.query(sql2, likeInfo, (err, result) => {
 
      if (err) return err;
      res.cc("点赞成功", 0);
    });
  });
};

// 查询点赞的wall_id 红心显示

/**
 *
 * @param {*} req
 * @param {*} res
 */
exports.findUserWallLike = (req, res) => {
  const sql = `select * from wall_like where user_id = ?`;
  db.query(sql, [req.user.id], (err, results) => {
    if (err) return err;
    res.send({
      message: "获取成功",
      status: 0,
      data: results,
    });
  });
};
